Total Complexity | 4 |
Total Lines | 32 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | import {ObserverAdapter, OnChangeCallback} from '@enbock/state-value-observer/ValueObserver'; |
||
7 | |||
8 | export default class DataStorage { |
||
9 | protected domain: string; |
||
10 | protected storage: Storage; |
||
11 | protected adapters: AdapterDictionary; |
||
12 | |||
13 | constructor(domain: string, storage: Storage) { |
||
14 | 3 | this.domain = domain; |
|
15 | 3 | this.storage = storage; |
|
16 | 3 | this.adapters = {}; |
|
17 | } |
||
18 | |||
19 | attach<Type>(key: string, adapter: ObserverAdapter<Type>): StorageAdapter<Type> { |
||
20 | 1 | const callback: OnChangeCallback<Type> = (newValue: Type) => this.updateStorage(key, newValue); |
|
21 | 1 | const storageAdapter: StorageAdapter<Type> = new StorageAdapter<Type>(adapter, callback); |
|
22 | 1 | this.adapters[key] = storageAdapter; |
|
23 | |||
24 | 1 | return storageAdapter; |
|
25 | } |
||
26 | |||
27 | loadData<Type>(key: string, initialValue: Type): Type { |
||
28 | 2 | const serializedJsonData: string | null = this.storage.getItem(this.domain + '::' + key); |
|
29 | 2 | let data: Type = initialValue; |
|
30 | 2 | if (serializedJsonData != null) { |
|
31 | 1 | data = JSON.parse(serializedJsonData) as Type; |
|
32 | } |
||
33 | |||
34 | 2 | return data; |
|
35 | } |
||
36 | |||
37 | protected updateStorage<Type>(key: string, newValue: Type) { |
||
38 | 1 | this.storage.setItem(this.domain + '::' + key, JSON.stringify(newValue)); |
|
39 | } |
||
41 |